<template>
  <view class="order-page">
    <!-- 订单状态筛选 -->
    <view class="order-tabs">
      <view
          class="tab-item"
          v-for="tab in tabList"
          :key="tab.key"
          :class="{ active: currentTab === tab.key }"
          @click="switchTab(tab.key)"
      >
        {{ tab.text }}
      </view>
    </view>

    <!-- 订单列表 -->
    <view class="order-list" @scrolltolower="loadMore">
      <!-- 订单项 -->
      <view
          class="order-item"
          v-for="(order, index) in filteredOrders"
          :key="order.id || index"
      >
        <!-- 订单头部 -->
        <view class="order-header">
          <view class="seller-info">
            <text class="seller-name">{{ order.sellerName || '未知商家' }}</text>
            <text
                class="order-status"
                :class="getStatusConfig(order.status).class"
            >
              {{ getStatusConfig(order.status).text }}
            </text>
          </view>
          <view class="order-time">订单编号: {{ order.orderNumber }}</view>
        </view>

        <!-- 订单商品信息 -->
        <view class="order-goods">
          <view class="goods-item" @click="goToGoodsDetail(order.itemId)">
            <image
                class="goods-image"
                :src="getFirstImage(order.itemImage)"
                mode="aspectFill"
                lazy-load
            ></image>
            <view class="goods-info">
              <view class="goods-title">{{ order.itemName || '商品名称' }}</view>
              <view class="goods-price">
                <text>¥{{ order.totalAmount || 0 }}</text>
                <text class="goods-count">x1</text>
              </view>
            </view>
          </view>
          <view class="order-total">
            合计: <text class="total-price">¥{{ order.totalAmount || 0 }}</text>
            <text class="discount"> (已优惠 ¥{{ order.couponAmount || 0 }})</text>
          </view>
        </view>

        <!-- 订单底部 -->
        <view class="order-footer">
          <view class="order-actions">
            <!-- 待支付状态（1）：取消订单 + 去付款 -->
            <button
                class="action-btn cancel-btn"
                v-if="order.status === 1"
                @click="cancelOrder(order.orderNumber, index)"
            >
              取消订单
            </button>
            <button
                class="action-btn pay-btn"
                v-if="order.status === 1"
                @click="payOrder(order.id)"
            >
              去付款
            </button>

            <!-- 已支付状态（2）/已发货状态（3）：确认收货 -->
            <button
                class="action-btn confirm-btn"
                v-if="order.status === 2 || order.status === 3"
                @click="confirmReceipt(order.id)"
            >
              确认收货
            </button>

            <!-- 已完成状态（4）：去评价 -->
            <button
                class="action-btn comment-btn"
                v-if="order.status === 4"
                @click="goToComment(order.id)"
            >
              去评价
            </button>

            <!-- 所有状态都显示订单详情 -->
            <button
                class="action-btn detail-btn"
                @click="viewOrderDetail(order.id)"
            >
              订单详情
            </button>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty-state" v-if="filteredOrders.length === 0 && !loading">
        <uni-icons type="order" size="60" color="#ccc"></uni-icons>
        <text class="empty-text">{{ getEmptyText() }}</text>
        <button class="empty-btn" @click="goToHome">去逛逛</button>
      </view>

      <!-- 加载状态 -->
      <view class="loading-state" v-if="loading">
        <uni-loading-icon size="24" color="#ff4d4f"></uni-loading-icon>
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 加载更多提示 -->
      <view class="loading-more" v-if="!loading && hasMore">
        <uni-loading-icon size="20" color="#999"></uni-loading-icon>
        <text>加载更多...</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { request } from '@/utils/request';
import {cancelOrderApi, confirmOrder, queryList} from "@/apis/orderApi";

// 订单状态配置（核心：支付后状态为2-已支付）
// 状态定义：1-待支付, 2-已支付, 3-已发货, 4-已完成, 5-已取消, 6-已评价
const ORDER_STATUS_CONFIG = {
  1: { key: 'unpaid', text: '待支付', class: 'unpaid', sortWeight: 1 },    // 待支付（优先级最高）
  2: { key: 'paid', text: '已支付', class: 'paid', sortWeight: 2 },        // 支付后状态（已支付）
  3: { key: 'shipped', text: '已发货', class: 'shipped', sortWeight: 3 },  // 已发货
  4: { key: 'completed', text: '已完成', class: 'completed', sortWeight: 4 }, // 已完成（待评价）
  6: { key: 'commented', text: '已评价', class: 'commented', sortWeight: 5 }, // 已评价
  5: { key: 'cancelled', text: '已取消', class: 'cancelled', sortWeight: 6 }  // 已取消（优先级最低）
};

// 生成筛选标签列表
const tabList = [
  { key: 'all', text: '全部' },
  ...Array.from(new Set(Object.values(ORDER_STATUS_CONFIG).map(status => ({
    key: status.key,
    text: status.text
  }))))
];

// 响应式数据
const orders = ref([]);
const currentTab = ref('all');
const loading = ref(true);
const pageNum = ref(1);
const pageSize = ref(10);
const total = ref(0);
const userInfo = uni.getStorageSync("userInfo") || {};

// 计算是否还有更多数据
const hasMore = computed(() => {
  return orders.value.length < total.value;
});

// 筛选并排序订单列表
const filteredOrders = computed(() => {
  let filtered = [];
  // 1. 筛选逻辑
  if (currentTab.value === 'all') {
    filtered = [...orders.value];
  } else {
    // 根据当前标签筛选对应状态的订单
    const targetStatus = Object.keys(ORDER_STATUS_CONFIG).find(
        key => ORDER_STATUS_CONFIG[key].key === currentTab.value
    );
    filtered = orders.value.filter(order => order.status === Number(targetStatus));
  }

  // 2. 排序逻辑（按状态优先级+创建时间倒序）
  return filtered.sort((a, b) => {
    const weightA = getStatusConfig(a.status).sortWeight || 99;
    const weightB = getStatusConfig(b.status).sortWeight || 99;

    // 优先级相同则按创建时间倒序（最新订单在前）
    if (weightA === weightB) {
      return new Date(b.createTime) - new Date(a.createTime);
    }
    return weightA - weightB; // 优先级低的排在后面
  });
});

// 获取状态配置信息
const getStatusConfig = (status) => {
  return ORDER_STATUS_CONFIG[status] || {
    text: '未知状态',
    class: 'unknown',
    sortWeight: 99
  };
};

// 空状态文本
const getEmptyText = () => {
  if (currentTab.value === 'all') return '暂无订单';
  const targetStatus = Object.values(ORDER_STATUS_CONFIG).find(
      item => item.key === currentTab.value
  );
  return `暂无${targetStatus?.text || '相关'}订单`;
};

// 处理商品图片（取第一张）
const getFirstImage = (imageStr) => {
  try {
    const images = JSON.parse(imageStr || '[]');
    return images[0] || '/static/images/default-goods.png';
  } catch (e) {
    console.error('解析图片地址失败:', e);
    return '/static/images/default-goods.png';
  }
};

// 页面初始化
onMounted(() => {
  fetchOrders();
  // 重置滚动位置
  uni.pageScrollTo({
    scrollTop: 0,
    duration: 0
  });
  // 监听页面触底事件
  uni.$on('onReachBottom', loadMore);
});

// 页面卸载时移除监听
onUnmounted(() => {
  uni.$off('onReachBottom', loadMore);
});

// 获取订单列表数据
const fetchOrders = async () => {
  try {
    loading.value = true;
    const params = {
      userId: userInfo.userId,
      pageNum: pageNum.value,
      pageSize: pageSize.value
    };

    // 如果筛选特定状态，添加状态参数
    if (currentTab.value !== 'all') {
      const targetStatus = Object.keys(ORDER_STATUS_CONFIG).find(
          key => ORDER_STATUS_CONFIG[key].key === currentTab.value
      );
      params.status = Number(targetStatus);
    }

    const res = await queryList(params);
    if (res.data.code === 200 && res.data.data) {
      // 分页数据处理
      if (pageNum.value === 1) {
        orders.value = res.data.data.list || [];
      } else {
        orders.value = [...orders.value, ...(res.data.data.list || [])];
      }
      total.value = res.data.data.total || 0;
    } else {
      orders.value = [];
      total.value = 0;
      uni.showToast({ title: res.data.msg || '获取订单失败', icon: 'none' });
    }
  } catch (err) {
    console.error('获取订单失败:', err);
    uni.showToast({ title: '网络错误，请重试', icon: 'none' });
  } finally {
    loading.value = false;
  }
};

// 切换筛选标签
const switchTab = (tabKey) => {
  if (currentTab.value === tabKey) return;
  currentTab.value = tabKey;
  pageNum.value = 1; // 重置页码
  fetchOrders(); // 重新加载数据
};

// 加载更多数据
const loadMore = () => {
  if (!loading.value && hasMore.value) {
    pageNum.value++;
    fetchOrders();
  }
};

// 取消订单
const cancelOrder = async (orderNumber, index) => {
  uni.showModal({
    title: '确认取消',
    content: '确定要取消该订单吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const res = await cancelOrderApi(orderNumber);
          if (res.data.code === 200) {
            uni.showToast({ title: '订单已取消', icon: 'success' });
            // 移除当前订单（本地更新）
            orders.value.splice(index, 1);
            // 1.5秒后刷新列表（可选）
            setTimeout(() => fetchOrders(), 1500);
          } else {
            uni.showToast({ title: res.data.msg || '取消失败', icon: 'none' });
          }
        } catch (err) {
          console.error('取消订单失败:', err);
          uni.showToast({ title: '网络错误，请重试', icon: 'none' });
        }
      }
    }
  });
};

// 去支付（仅待支付状态）
const payOrder = (orderId) => {
  uni.navigateTo({ url: `/pages/shop/shop-play?orderId=${orderId}` });
};

// 查看订单详情
const viewOrderDetail = (orderId) => {
  uni.navigateTo({ url: `/pages/order-detail/order-detail?orderId=${orderId}` });
};

// 去评价（仅已完成状态）
const goToComment = (orderId) => {
  uni.navigateTo({ url: `/pages/shop/shop-comment?orderId=${orderId}` });
};

// 确认收货（已支付/已发货状态）
const confirmReceipt = (orderId) => {
  uni.showModal({
    title: '确认收货',
    content: '请确认已收到商品，确认后订单状态将变为"已完成"',
    success: async (res) => {
      if (res.confirm) {
        try {
          const res = await confirmOrder(orderId)
          if (res.data.code === 200) {
            uni.showToast({ title: '确认收货成功', icon: 'success' });
            // 刷新订单列表（状态更新为已完成）
            fetchOrders();
          } else {
            uni.showToast({ title: res.data.msg || '操作失败', icon: 'none' });
          }
        } catch (err) {
          console.error('确认收货失败:', err);
          uni.showToast({ title: '网络错误，请重试', icon: 'none' });
        }
      }
    }
  });
};

// 查看商品详情
const goToGoodsDetail = (itemId) => {
  if (itemId) {
    uni.navigateTo({ url: `/pages/shop/shop-detail?itemId=${itemId}` });
  }
};

// 去首页
const goToHome = () => {
  uni.switchTab({ url: '/pages/shop/shop' });
};
</script>

<style scoped>
:root {
  --primary-color: #ff4d4f;
  --border-color: #f5f5f5;
  --text-primary: #333;
  --text-secondary: #666;
  --text-tertiary: #999;
  --gap-sm: 8px;
  --gap-md: 16px;
  --radius: 8px;
}

.order-page {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
  font-size: 14px;
}

/* 订单状态筛选标签 */
.order-tabs {
  display: flex;
  height: 48px;
  background-color: #fff;
  border-bottom: 1px solid var(--border-color);
  position: sticky;
  top: 0;
  z-index: 10;
  overflow-x: auto;
  scrollbar-width: none;
}

.order-tabs::-webkit-scrollbar {
  display: none;
}

.tab-item {
  flex: 0 0 auto;
  padding: 0 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  color: var(--text-secondary);
  position: relative;
  white-space: nowrap;
}

.tab-item.active {
  color: var(--primary-color);
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 40px;
  height: 2px;
  background-color: var(--primary-color);
  border-radius: 2px;
}

/* 订单列表容器 */
.order-list {
  padding-bottom: var(--gap-md);
  height: calc(100vh - 48px); /* 减去标签栏高度 */
  overflow-y: auto;
  scroll-padding-bottom: 50px;
}

/* 订单项样式 */
.order-item {
  background-color: #fff;
  border-radius: var(--radius);
  margin: var(--gap-md);
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 订单头部 */
.order-header {
  padding: 12px var(--gap-md);
  border-bottom: 1px solid var(--border-color);
}

.seller-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.seller-name {
  font-size: 16px;
  color: var(--text-primary);
  font-weight: 500;
}

.order-status {
  font-size: 14px;
  padding: 2px 8px;
  border-radius: 12px;
}

/* 状态样式 */
.order-status.unpaid {
  color: #fa8c16;
  background-color: #fff8f0; /* 待支付-橙色背景 */
}

.order-status.paid {
  color: #52c41a;
  background-color: #f6ffed; /* 已支付-绿色背景 */
}

.order-status.shipped {
  color: #1890ff;
  background-color: #e6f7ff; /* 已发货-蓝色背景 */
}

.order-status.completed {
  color: #722ed1;
  background-color: #f9f0ff; /* 已完成-紫色背景 */
}

.order-status.cancelled {
  color: #bfbfbf;
  background-color: #f5f5f5; /* 已取消-灰色背景 */
}

.order-status.commented {
  color: #ff4d4f;
  background-color: #fff1f0; /* 已评价-红色背景 */
}

.order-time {
  font-size: 12px;
  color: var(--text-tertiary);
}

/* 商品信息 */
.order-goods {
  padding: 12px var(--gap-md);
}

.goods-item {
  display: flex;
  margin-bottom: 12px;
  cursor: pointer;
}

.goods-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  margin-right: 12px;
  flex-shrink: 0;
  background-color: #f5f5f5;
}

.goods-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  min-height: 80px;
}

.goods-title {
  font-size: 14px;
  color: var(--text-primary);
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.goods-price {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.goods-price text {
  font-size: 14px;
  color: var(--primary-color);
  font-weight: 500;
}

.goods-count {
  font-size: 12px;
  color: var(--text-secondary);
}

/* 订单底部 */
.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px var(--gap-md);
  border-top: 1px solid var(--border-color);
}

.order-total {
  font-size: 14px;
  color: var(--text-secondary);
}

.total-price {
  font-size: 16px;
  color: var(--primary-color);
  font-weight: 500;
  margin-left: 4px;
}

.discount {
  font-size: 12px;
  color: var(--text-tertiary);
  margin-left: 8px;
}

.order-actions {
  display: flex;
  gap: var(--gap-sm);
}

/* 按钮样式 */
.action-btn {
  height: 32px;
  line-height: 32px;
  padding: 0 16px;
  border-radius: 4px;
  font-size: 14px;
  border: none;
}

.cancel-btn {
  color: var(--text-secondary);
  background-color: var(--border-color);
}

.pay-btn {
  color: #fff;
  background-color: var(--primary-color);
}

.confirm-btn {
  color: #fff;
  background-color: #1890ff;
}

.comment-btn {
  color: #fff;
  background-color: #fa8c16;
}

.detail-btn {
  color: var(--text-secondary);
  background-color: #fff;
  border: 1px solid #ddd;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
  color: var(--text-tertiary);
}

.empty-text {
  margin: 20px 0 24px;
  font-size: 16px;
}

.empty-btn {
  height: 40px;
  line-height: 40px;
  padding: 0 24px;
  background-color: var(--primary-color);
  color: #fff;
  border-radius: 20px;
  font-size: 14px;
  border: none;
}

/* 加载状态 */
.loading-state, .loading-more {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 30px 0;
  color: var(--text-tertiary);
  font-size: 14px;
}

.loading-more {
  flex-direction: row;
  gap: 8px;
}

/* 未知状态样式 */
.order-status.unknown {
  color: var(--text-tertiary);
  background-color: var(--border-color);
}
</style>